import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Link, routerRedux } from 'dva/router';
import { connect } from 'dva';
import {
  Table,
  Icon,
  Divider,
  Form,
  Select,
  DatePicker,
  Input,
  Card,
  Tag,
  Avatar,
  Checkbox,
  Rate,
  Progress,
  Button,
  message,
  Row,
  Col,
  Modal,
  Collapse,
  List,
  Radio,
  Spin,
} from 'antd';
import querystring from 'querystring';
import FooterToolbar from 'components/FooterToolbar';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import CustomerInfoEditor from '../../../components/Falcon/CustomerInfoEditor';

import styles from './style.less';

const Panel = Collapse.Panel;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Option } = Select;
const { TextArea } = Input;

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

const CUSTOMER_STATE_SELF = 1;
const CUSTOMER_STATE_PAYER = 2;
const CUSTOMER_STATE_GUARANTOR = 3;

@connect(({ apply }) => ({
  apply,
}))
@Form.create()
export default class CreateApply extends PureComponent {
  state = {
    width: '100%',
    productValue: null,
    id: '',
    taskId: '',
    type: '',
    applyDetailsValue: null,
  };

  guranteerEditorList = [];
  payerEditorList = [];

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    // console.log("parMS", params)

    dispatch({ type: 'apply/getProductList' });

    if (params.id) {
      this.setState({
        id: params.id,
        taskId: params.taskId,
        type: params.type,
      });
      dispatch({
        type: 'apply/getCreateApplyDetails',
        payload: {
          projectId: params.id,
        },
        callback: () => {
          const { apply: { applyDetails } } = this.props;
          if (applyDetails) {
            this.setState({
              applyDetailsValue: applyDetails,
              productValue: applyDetails.productId,
            });
          }
        },
      });
    } else {
      dispatch({
        type: 'apply/toogleLoadStatus',
        payload: true,
      });
    }
  }

  // resizeFooterToolbar = () => {
  //   const sider = document.querySelectorAll('.ant-layout-sider')[0];
  //   const width = `calc(100% - ${sider.style.width})`;
  //   if (this.state.width !== width) {
  //     this.setState({ width });
  //   }
  // };

  /**
   * lify cycle methods
   */

  componentWillUnmount() {
    //this.props.dispatch({ type: 'examination/clearPage' })
    // console.log('CreateApply componentWillUnmount');

    this.props.dispatch({ type: 'apply/clearPage' });
  }

  /**
   * even handler
   */

  /**
   * user action methods
   */
  hanleAddGuarantorClick = () => {
    const { apply, dispatch } = this.props;
    const { customers } = apply;
    // const newRecord = customers
    const newCustomer = {
      role: { key: 'guarantor', name: '担保人' },
      name: '',
      description: '',
      key: `${customers.length + 1}`,
      id: `${customers.length + 1}`,
      documentList: [],
      thridVerifyList: [],
      state: CUSTOMER_STATE_GUARANTOR,
      type: this.state.type,
    };

    dispatch({
      type: 'apply/addCustomer',
      payload: newCustomer,
    });
  };

  hanleAddPayerClick = () => {
    const { apply, dispatch } = this.props;
    const { customers } = apply;
    // const newRecord = customers
    const newCustomer = {
      role: { key: 'payer', name: '共同还款人' },
      name: '',
      description: '',
      key: `${customers.length + 1}`,
      id: `${customers.length + 1}`,
      documentList: [],
      thridVerifyList: [],
      state: CUSTOMER_STATE_PAYER,
      type: this.state.type,
    };
    dispatch({
      type: 'apply/addCustomer',
      payload: newCustomer,
    });
  };

  /**
   * render methods
   */
  renderPanelHeader = () => {
    return (
      <div>
        客户姓名：<Input style={{ width: '100px' }} />
        身份证：<Input style={{ width: '100px' }} />
        联系电话：<Input style={{ width: '100px' }} />
        关系<Select style={{ width: '100px' }} />
        <Button>保存</Button>
      </div>
    );
  };

  saveFormRef = formRef => {
    // console.log('handleSubmit', formRef);
    this.formRef = formRef;
  };

  saveFormRefOfGuarantor = formRef => {
    //console.log("handleSubmit", formRef)
    // this.formRefOfGuarantor = formRef;
    this.guranteerEditorList.push(formRef);
  };

  saveFormRefOfPayer = formRef => {
    // console.log('handleSubmit', formRef);
    //this.formRefOfPayer = formRef;
    this.payerEditorList.push(formRef);
  };

  handleCustomerSelected = customer => {
    //changeMainApplyer
    // console.log("handleCustomerSelected", customer)
    this.props.dispatch({
      type: 'apply/changeMainApplyer',
      payload: {
        customer,
      },
    });
  };

  handleGuarantorListSelected = (guarantor, index) => {
    //changeMainApplyer
    //  console.log('handleGuarantorListSelected',guarantor);
    this.props.dispatch({
      type: 'apply/changeGuarantor',
      payload: {
        guarantor,
        index,
      },
    });
  };

  handlePayerSelected = (payer, index) => {
    // console.log('handlePayerSelected',payer);
    this.props.dispatch({
      type: 'apply/changePayer',
      payload: {
        payer,
        index,
      },
    });
  };

  handleCustomerImageUploaded = (customerInfo, fieldName, imageList, type) => {
    // console.log("handleCustomerImageUploaded type: ", type)
    this.props.dispatch({
      type: 'apply/changeImageForCustomer',
      payload: {
        customerInfo: customerInfo,
        fieldName: fieldName,
        imageList: imageList,
        type: type,
      },
    });
  };

  handleSubmit = () => {
    // console.log('this.formRef=', this.formRef);
    let isGuranteerInfoOk = true;
    let guranteerValues = [];
    this.guranteerEditorList.map(formRef => {
      const { validateFieldsAndScroll } = formRef.props.form;
      validateFieldsAndScroll((error, values) => {
        if (error) {
          // console.log('sub form values', values);
          isGuranteerInfoOk = false;
          //this.validateSubForm2();
        } else {
          guranteerValues.push(values);
        }
      });
    });

    if (isGuranteerInfoOk) {
      // console.log('sub form guranteerValues', guranteerValues);
      this.validateSubForm2(guranteerValues);
    }
  };

  validateSubForm2 = guranteerValues => {
    // console.log('this.formRef=', this.formRef);

    let isPayerInfoOk = true;
    let payerValues = [];
    this.payerEditorList.map(formRef => {
      //const { validateFieldsAndScroll } = formRef.props.form;
      const { error, values } = formRef.collectCustomerInfo();

      if (error) {
        // console.log('sub form values', values);
        isPayerInfoOk = false;
        //this.validateSubForm2();
      } else {
        payerValues.push(values);
      }
    });

    if (isPayerInfoOk) {
      // console.log('sub form guranteerValues', guranteerValues);
      // console.log('sub form payerValues', payerValues);

      this.submitToServer(null, guranteerValues, payerValues);
    }
  };

  submitToServer = (mainPayerImages, gurantorsImages, payerImages) => {
    //console.log('sub form guranteerValues', guranteerValues);

    const { apply, dispatch } = this.props;
    const { customers } = apply;
    // console.log('sub form payerValues', customers);
    if (this.state.productValue) {
      if (this.state.type == 1) {
        //驳回后修改提交
        dispatch({
          type: 'apply/updateStartApply',
          payload: {
            customerIdRelation: customers,
            taskId: this.state.taskId,
            projectId: this.state.id,
            productId: this.state.productValue,
          },
          callback: () => {
            const { apply: { applyResult } } = this.props;
            if (applyResult.code == 200) {
              message.success('提交成功');
              dispatch(routerRedux.push('/apply/CreateApplyList'));
            } else {
              message.error(applyResult.message);
            }
          },
        });
      } else {
        dispatch({
          //第一次业务申请
          type: 'apply/createApply',
          payload: {
            customerIdRelation: customers,
            productId: this.state.productValue,
          },
          callback: () => {
            const { apply: { applyResult } } = this.props;
            if (applyResult.code == 200) {
              message.success('提交成功');
              dispatch(routerRedux.push('/apply/CreateApplyList'));
            } else {
              message.error(applyResult.message);
            }
          },
        });
      }
    } else {
      message.warning('请选择产品');
    }
  };

  renderOption = data => {
    const options = [];
    data.map(item => {
      options.push(<Option value={item.id}>{item.productName}</Option>);
    });
    return options;
  };

  handleRoleListChange = value => {
    // console.log('value', value);
    this.setState({
      productValue: value,
    });
  };

  calcCustomer = () => {
    const { apply } = this.props;
    const { customers } = apply;
    // console.log("item => item.state", customers)
    const customerList = customers && customers.filter(item => item.state == CUSTOMER_STATE_SELF);
    const customer = customerList.length > 0 ? customerList[0] : null;
    return customer;
  };
  render() {
    const { apply } = this.props;
    return (
      <PageHeaderLayout title="业务申请">
        {apply.isLoaded ? (
          this.renderMainContent()
        ) : (
          <div className={styles.spinContainer}>
            <Spin size="large" />
          </div>
        )}
      </PageHeaderLayout>
    );
  }

  handleRemoveParticipant = (item, state) => {
    // console.log("sadasdasdasda", item)
    Modal.confirm({
      title: `你确定要删除${state == 2 ? '担保人' : '共同还款人'}吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (this.state.type == 1 && item.type != '1') {
          //驳回后修改提交
          const { dispatch } = this.props;
          dispatch({
            type: 'apply/toogleLoadStatus',
            payload: false,
          });
          dispatch({
            type: 'apply/deleteRelation',
            payload: {
              relationId: item.relationId,
            },
            callback: () => {
              const { apply: { applyResult } } = this.props;
              if (applyResult.code == 200) {
                message.success('删除成功');
                dispatch({
                  type: 'apply/getCreateApplyDetails',
                  payload: {
                    projectId: this.state.id,
                  },
                });
                dispatch({
                  type: 'apply/toogleLoadStatus',
                  payload: true,
                });
              } else {
                message.error(applyResult.message);
              }
            },
          });
        } else {
          const { dispatch } = this.props;
          dispatch({
            type: 'apply/removeCustomer',
            payload: item,
          });
          message.success('删除成功');
        }
      },
    });
  };

  handleCustomerImageRemove = (fieldName, fileInfo) => {
    // console.log("handleCustomerImageRemove", fileInfo)
    const { dispatch } = this.props;

    dispatch({
      type: 'apply/deleteFile',
      payload: {
        fileId: fileInfo.key,
      },
    });
  };

  renderGuarantorPanelTitle = item => {
    // console.log("renderGuarantorPanelTitle", item)
    return (
      <Row>
        <Col span={4}>
          <span style={{}}>{'担保人'}</span>
        </Col>
        <div>
          <Col span={18} />
          <div
            style={{ float: 'right', marginRight: '40px' }}
            onClick={e => {
              e.stopPropagation();
            }}
          >
            <Col span={2} style={{ textAlign: 'center' }}>
              <Icon type="close" onClick={() => this.handleRemoveParticipant(item, 2)} />
            </Col>
          </div>
        </div>
      </Row>
    );
  };

  renderPayerPanelTitle = item => {
    return (
      <Row>
        <Col span={4}>
          <span style={{}}>{'共同还款人'}</span>
        </Col>
        <div>
          <Col span={18} />
          <div
            style={{ float: 'right', marginRight: '40px' }}
            onClick={e => {
              e.stopPropagation();
            }}
          >
            <Col span={2} style={{ textAlign: 'center' }}>
              <Icon type="close" onClick={() => this.handleRemoveParticipant(item, 3)} />
            </Col>
          </div>
        </div>
      </Row>
    );
  };

  handleCallback = () =>{
    window.history.back(-1)
  }

  renderMainContent() {
    const { apply } = this.props;
    const { customers, applyBusinessLoading } = apply;
    const { applyProductList, applyDetails } = apply;
    const { getFieldDecorator } = this.props.form;

    const customer = this.calcCustomer();
    const guarantorList =
      customers && customers.filter(item => item.state == CUSTOMER_STATE_GUARANTOR);
    const payerList = customers && customers.filter(item => item.state == CUSTOMER_STATE_PAYER);
    // console.log("guarantorList", guarantorList)
    // console.log("payerList", payerList)

    return (
      <div> 
        {
          <div>
            <Card>
              <CustomerInfoEditor
                wrappedComponentRef={this.saveFormRef}
                data={customer}
                typeState={this.state.type}
                onCustomerSelected={this.handleCustomerSelected}
                onCustomerImageUploaded={this.handleCustomerImageUploaded}
                // onCustomerImageRemove={this.handleCustomerImageRemove}
              />
            </Card>
            <Button
              onClick={this.hanleAddGuarantorClick}
              style={{ width: '100%', marginTop: '15px' }}
              type="dashed"
              icon="plus"
            >
              添加担保人
            </Button>
            <Button
              onClick={this.hanleAddPayerClick}
              style={{ width: '100%', marginTop: '15px' }}
              type="dashed"
              icon="plus"
            >
              添加共同还款人
            </Button>
            {guarantorList &&
              guarantorList.map((item, index) => (
                <Collapse bordered={true} style={{ marginTop: '15px' }} key={index}>
                  <Panel key="1" header={this.renderGuarantorPanelTitle(item)}>
                    <CustomerInfoEditor
                      isForFamilyMember={true}
                      data={item}
                      mainApplyer={customer}
                      wrappedComponentRef={this.saveFormRefOfGuarantor}
                      onCustomerSelected={guarantor =>
                        this.handleGuarantorListSelected(guarantor, index)
                      }
                      onCustomerImageUploaded={this.handleCustomerImageUploaded}
                    />
                  </Panel>
                </Collapse>
              ))}

            {payerList &&
              payerList.map((item, index) => (
                <Collapse bordered={true} style={{ marginTop: '15px' }} key={index}>
                  <Panel key="2" header={this.renderPayerPanelTitle(item)}>
                    <CustomerInfoEditor
                      isForFamilyMember={true}
                      data={item}
                      mainApplyer={customer}
                      wrappedComponentRef={this.saveFormRefOfPayer}
                      onCustomerSelected={payer => this.handlePayerSelected(payer, index)}
                      onCustomerImageUploaded={this.handleCustomerImageUploaded}
                      //onCustomerSelected={(guarantor)=>this.handleGuarantorListSelected(guarantor,index)}
                    />
                  </Panel>
                </Collapse>
              ))}
            <Card className={styles.productFormCard} style={{ marginTop: '15px' }}>
              <Form className={styles.productForm}>
                <FormItem label="产品" {...formItemLayout}>
                  <Select
                    style={{ width: '80%' }}
                    placeholder="请选择"
                    value={this.state.productValue}
                    onChange={this.handleRoleListChange}
                  >
                    {applyProductList && this.renderOption(applyProductList)}
                  </Select>
                </FormItem>
              </Form>
            </Card>
          </div>
        }

        <FooterToolbar style={{ width: this.state.width }}>
          <Button type="primary" onClick={this.handleSubmit} loading={applyBusinessLoading}>
            提交
          </Button>
          <Button  onClick={this.handleCallback}>
            返回
          </Button>
        </FooterToolbar>
      </div>
    );
  }
}
